<template>
  <div class="el_main_con">
    <Breadcrumb></Breadcrumb>
    <el-card>
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" effect="dark">
      </el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类级联 -->
          <el-cascader v-model="catVal" :options="catLevelOptions" @change="catLevelChange" :props="catecadeProps" clearable></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isAbled" @click="showAddCatDialog = true">添加参数</el-button>
          <el-table :data="attributesManyList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
                <div class="tagInput">
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" @click="askDel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isAbled" @click="showAddCatDialog = true">添加属性</el-button>
          <el-table :data="attributesOnlyList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
                <div class="tagInput">
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" @click="askDel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog :title="paramsOrAttribute" :visible.sync="showAddCatDialog" width="30%">
      <el-form :model="addCateForm" :rules="addCateForm" ref="addCateForm" label-width="100px">
        <el-form-item :label="paramsOrAttributeTit" prop="attr_name">
          <el-input v-model="addCateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddCatDialog = false">取 消</el-button>
        <el-button type="primary" @click="postAddCateForm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from 'components/breadcrumb/breadcrumb'
import { Categories } from '@/api/apiConfig'
export default {
  components: {
    Breadcrumb
  },
  data () {
    return {
      catVal: '',
      catLevelOptions: [],
      catecadeProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      catId: '',
      attributesManyList: [],
      attributesOnlyList: [],
      showAddCatDialog: false,
      addCateForm: {
        attr_name: ''
      },
      isEdit: false,
      attrId: '',
      inputVisible: false,
      inputValue: ''
    }
  },
  computed: {
    isAbled () {
      if (this.catVal.length !== 3) {
        return true
      }
      return false
    },
    paramsOrAttribute () {
      if (this.activeName === 'many') {
        return '添加动态参数'
      }
      return '添加静态属性'
    },
    paramsOrAttributeTit () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  mounted () {
    this.getParentCateList()
  },
  methods: {
    getParentCateList () {
      const params = {
        type: 3
      }
      Categories.getCategories(params).then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.catLevelOptions = res.data
      })
    },
    catLevelChange () {
      if (this.catVal.length !== 3) {
        this.catVal = []
        this.attributesManyList = []
        this.attributesOnlyList = []
        return false
      }
      this.catId = this.catVal[2]
      this.getattributeslist()
    },
    getattributeslist () {
      const url = `categories/${this.catId}/attributes`
      const params = {
        sel: this.activeName
      }
      Categories.getCatAttributes(url, params).then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        if (this.activeName === 'many') {
          this.attributesManyList = res.data
        } else {
          this.attributesOnlyList = res.data
        }
      })
    },
    handleTabsClick () {
      this.getattributeslist()
    },
    openEditDialog (row) {
      this.isEdit = true
      this.showAddCatDialog = true
      this.addCateForm.attr_name = row.attr_name
      this.attrId = row.attr_id
    },
    askDel (row) {
      this.attrId = row.attr_id
      this.$confirm('确定删除该参数?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = `categories/${this.catId}/attributes/${this.attrId}`
        Categories.deleteCatAttributes(url).then(res => {
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getattributeslist()
        })
      }).catch(() => { })
    },
    postAddCateForm () {
      if (this.isEdit === true) {
        this.showAddCatDialog = false
        const url = `categories/${this.catId}/attributes/${this.attrId}`
        const params = {
          attr_name: this.addCateForm.attr_name,
          attr_sel: this.activeName
        }
        Categories.editCatAttributes(url, params).then(res => {
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.showAddCatDialog = false
          this.$refs.addCateForm.resetFields()
          this.getattributeslist()
        })
      } else {
        const url = `categories/${this.catId}/attributes`
        const params = {
          attr_name: this.addCateForm.attr_name,
          attr_sel: this.activeName
        }
        Categories.postCatAttributes(url, params).then(res => {
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.showAddCatDialog = false
          this.$refs.addCateForm.resetFields()
          this.getattributeslist()
        })
      }
      this.isEdit = false
    },

    showInput (row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
      } else {
        row.attr_vals.push(row.inputValue.trim())
        row.inputVisible = false
        row.inputValue = ''
        this.savePutcategories(row)
      }
    },
    savePutcategories (row) {
      const url = `categories/${this.catId}/attributes/${row.attr_id}`
      const params = {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      }
      Categories.putCatAttributes(url, params).then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
      })
    },
    // 删除对应参数的选项
    handleClose (index, row) {
      row.attr_vals.splice(index, 1)
      this.savePutcategories(row)
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 0 5px;
}
.tagInput {
  display: inline-block;
  width: 150px;
}
</style>
